<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/1 0001
 * Time: 13:46
 */

namespace app\currency\controller;


use library\Controller;
use think\Db;

/**
 * 地址库管理
 * Class Cities
 * @package app\currency\controller
 */
class Cities extends Controller
{
    protected $table = 'Cities';

    /**
     * 地址库管理
     * @menu true
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '地址列表';
        $pid = $this->request->get('pid',0);
        $where = [['pid','eq',$pid]];
        $this->_query($this->table)->where($where)->like('name,adcode')->equal('status')->page();
    }

    /**
     * 添加地址和
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->_form($this->table,'form');
    }

    /**
     * 编辑地址
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->_form($this->table,'form');
    }
    protected function _form_filter(&$vo)
    {
        if ($this->request->isGet()) {
            // 选择自己的上级菜单
            if (empty($vo['pid']) && $this->request->get('pid', '0')) $vo['pid'] = $this->request->get('pid', '0');
            $this_city = Db::name($this->table)->where('id','eq',$vo['pid'])->find();
            // 列出可选上级菜单
            $menus = Db::name($this->table)->where(['status' => '1','pid' => $this_city['pid']])->order('id asc')->column('id,pid,name');
            $this->menus = $menus;
            if (isset($vo['id'])) foreach ($this->menus as $key => $menu) if ($menu['id'] === $vo['id']) $vo = $menu;
            $this->is_custom = false;
            if (empty($vo['level'])) $vo['level'] = 'custom';
            if(isset($vo['level']) && $vo['level'] == 'custom') $this->is_custom = true;
            //拆分经纬度
            if(isset($vo['center'])){
                list($vo['lng'],$vo['lat']) = explode(',',$vo['center']);
            }
        } else {
            if(!isset($vo['level']) || $vo['level'] != 'custom'){
                $this->error('非自定义地址无法修改！');
            }
            if(isset($vo['lng']) && isset($vo['lat'])){
                $vo['center'] = implode([$vo['lng'],$vo['lat']],',');
                unset($vo['lnt']);unset($vo['lat']);
            }
        }
    }
    public function add_house()
    {
        $this->title = '添加小区';
        if($this->request->isGet())
        {
            $this->fetch();
        } else {

            list($list, $idxs, $post) = [[], [], $this->request->post()];
            foreach (array_keys($post) as $key) if (stripos($key, 'name_') !== false) {
                $idxs[] = str_replace('name_', '', $key);
            }
            foreach (array_unique($idxs) as $index)  $list[] = [
                'name'      => $post["name_{$index}"] ?: ((string)($index+1)).'栋',
                'floor'     => $post["floor_{$index}"] ?: 1,
                'household' => $post["household_{$index}"] ?: 1
            ];
            $village_name = $post['village_name'];
            $city_id = $post['city_id'];
            $center = $post['center'];
            if ($city_id == '') {
                $this->error('请选择小区所在街道！');
            }
            if ($village_name == '') {
                $this->error('请输入小区名称！');
            }
            //添加小区
            $village_id = Db::name('Cities')->insertGetId([
                'name' => $village_name,
                'center' => $center,
                'level' => 'custom',
                'pid' => $city_id
            ]);
            //添加楼栋
            foreach ($list as $item) {
                $car_id = Db::name('Cities')->insertGetId([
                    'name' => $item['name'],
                    'center' => $center,
                    'level' => 'custom',
                    'pid' => $village_id
                ]);
                //添加楼层
                for($i=1;$i<=$item['floor'];$i++){
                    $floor_id = Db::name('Cities')->insertGetId([
                        'name' => $i . '楼',
                        'center' => $center,
                        'level' => 'custom',
                        'pid' => $car_id
                    ]);
                    for($j=1;$j<=$item['household'];$j++){
                        $household_name = $j > 9 ? $j : '0'.$j;
                        Db::name('Cities')->insertGetId([
                            'name' => $i . '-' . $household_name,
                            'center' => $center,
                            'level' => 'custom',
                            'pid' => $floor_id
                        ]);
                    }
                }
            }
            $this->success('添加小区成功！');
        }
    }
    public function getArrSet($arrs,$_current_index=-1)
    {
        //总数组
        static $_total_arr;
        //总数组下标计数
        static $_total_arr_index;
        //输入的数组长度
        static $_total_count;
        //临时拼凑数组
        static $_temp_arr;
        //进入输入数组的第一层，清空静态数组，并初始化输入数组长度
        if($_current_index<0)
        {
            $_total_arr=array();
            $_total_arr_index=0;
            $_temp_arr=array();
            $_total_count=count($arrs)-1;
            $this->getArrSet($arrs,0);
        }
        else
        {
            //循环第$_current_index层数组
            foreach($arrs[$_current_index] as $v)
            {
                //如果当前的循环的数组少于输入数组长度
                if($_current_index<$_total_count)
                {
                    //将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index]=$v;
                    //继续循环下一个数组
                    $this->getArrSet($arrs,$_current_index+1);
                }
                //如果当前的循环的数组等于输入数组长度(这个数组就是最后的数组)
                else if($_current_index==$_total_count)
                {
                    //将当前数组循环出的值放入临时数组
                    $_temp_arr[$_current_index]=$v;
                    //将临时数组加入总数组
                    $_total_arr[$_total_arr_index]=$_temp_arr;
                    //总数组下标计数+1
                    $_total_arr_index++;
                }
            }
        }
        return $_total_arr;
    }
    public function arr2x($arr1,$arr2)
    {
        $list = [];
        foreach ($arr1 as $item1) {
            foreach ($arr2 as $item2) {
                $list[] = $item1.'-'.$item2;
            }
        }
        return $list;
    }
    /**
     * 禁用地址
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用地址
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }
    protected function _save_filter()
    {
        $id = $this->request->post('id');
        if(Db::name($this->table)->where('id','eq',$id)->value('level') !== 'custom'){
            $this->error('非自定义地址无法修改！');
        }
    }

    /**
     * 删除地址
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }
    protected function _delete_filter()
    {
        $id = $this->request->post('id');
        if(Db::name($this->table)->where('id','eq',$id)->value('level') !== 'custom'){
            $this->error('非自定义地址无法删除！');
        }
    }
}